<template>
	<view class="indexBig">
		<view class="top">
			<text>全部订单</text>
			<view class="note" v-if="isDing && companyId == '2ab6d1'" @click="goToPage('confirm')">
				订单确认
			</view>
		</view>
		<view class="walletBox" v-if="companyInfo.realNameLogin == 1||companyInfo.isOpenPersonalPay=='yes'">
			<view class="">
				<uni-icons type="wallet" style="margin-right: 16rpx;"></uni-icons>余额
			</view>
			<view class="">¥{{ balance }}</view>
		</view>
		<view class="walletBox orderBox" @click="editMyAccount">
			<view class="">
				<uni-icons type="smallcircle" style="margin-right: 16rpx;"></uni-icons> 退出登录
			</view>
		</view>
		<!-- 搜索栏 -->
		<view class="searchBox">
			<u-icon name="search" size="42" color="#ccc"></u-icon>
			<u-input type="text" placeholder="搜索你想要的内容" v-model="storeName" confirm-type="search" :clearable="false"
				@confirm="_getOrderList"></u-input>
			<view class="" @click="_getOrderList">搜索</view>
		</view>

		<view class="allBox">
			<template v-if="orderList.length != 0">
				<view v-for="(item, index) in orderList" :key="index">
					<view class="list">
						<view class="listTop">
							<image :src="item.logo | getImg" mode=""></image>
							<view class="">{{ item.storeName }}</view>
							<!-- <view class="">{{ orderStateText(item.orderState) }}</view> -->
							<view class="">
								{{
									item.orderState == 'canceled' ? '已取消' : item.orderState == 'uncompleted' ? '已下单' :
										item.orderState == 'wait' ? '待付款' : item.orderState == 'pay' ? '已支付' : '已完成'
								}}
							</view>
							<!-- <view class="">{{item.stateName}}</view> -->
						</view>
						<view class="content">
							<div class="imgContent"
								:style="{ width: (item.companyOrderDaos.length + 1) * 170 + 'rpx' }">
								<view class="foodContent" v-for="(foodItem, foodIndex) in item.companyOrderDaos"
									:key="foodIndex">
									<image :src="foodItem.food.food.foodPic | getImg" mode="aspectFill"></image>
									<text>{{ foodItem.food.food.foodName }}X{{ foodItem.food.foodNum }}</text>
								</view>
							</div>
						</view>
					</view>
					<view class="orderInfo">取餐地址：{{ item.pickupAddress }} 取餐号：{{ item.pickingSerialNo }}号</view>
					<view class="afterSales" v-if="item.companyOrderAfterSalesState == '未处理'">您已提交售后申请，请等待商家处理</view>
					<view class="bottom">
						<view class="show-time" v-if='item.provideTime'>取餐日期：{{ item.provideTime }}</view>
						<view class="show-time" v-else>{{ item.createTime }}</view>
						<view class="">
							<view class="button" v-if="showCancelOrder(item)" @click="showCancelModal(index)">取消订单
							</view>
							<view class="button" v-if="!item.companyOrderAfterSalesState && item.canAfterSales"
								@click="goToPage('afterSales', item)">申请售后</view>
							<view class="button" v-if="item.companyOrderAfterSalesState == '已驳回'"
								@click="goToPage('feedback', item.companyOrderAfterSalesId)">售后被驳回</view>
							<view class="button" v-if="item.companyOrderAfterSalesState == '已处理'">已同意售后</view>
						</view>
					</view>
				</view>
			</template>
			<view class="empty" v-if="orderList.length == 0"><u-empty text="暂时还没有订单哦" mode="page"></u-empty></view>
		</view>
		<u-modal v-model="visiable" :content="'是否确认取消订单'" :showCancelButton="true" @confirm="confirm"
			@cancel="cancel"></u-modal>
		<view class="warnBox" :class="{ warnBoxShow: warnShow }">
			<view class="">{{ warnText }}</view>
		</view>

		<commen-footer :checkIndex="2"></commen-footer>
	</view>
</template>

<script>
	import {
		getMyOrderList,
		getOrderListWithCompany,
		cancelOrderWithCompany,
		getMyInfo,
		loginForCompany,
		getOrderListWithCompanyByPage,
		getSurplusSubsidyMoney
	} from '@/utils/req/api.js';
	import CommenHeader from '@/components/header/header.vue';
	import CommenFooter from '@/components/footer/companyFooter.vue';
	export default {
		components: {
			CommenHeader,
			CommenFooter
		},
		data() {
			return {
				orderList: [],

				pageNo: 1,
				pageSize: 10,
				moreOrderFlag: false,
				storeName: '',

				showAddressImg: false,
				addressImgArr: [],

				visiable: false,
				checkOrderIndex: '',
				// orderDetInfo: '',

				warnShow: false,
				warnText: '',

				isDing: false,
				companyId: '',

				companyInfo: '',
				myInfo: '',
				surplusSubsidyAmount: 0,

				hasLogin: false,
			};
		},
		onShow() {
			this.companyInfo = uni.getStorageSync('companyInfo');
			this.initUser();
			this.isDing = uni.getStorageSync('clientId') && uni.getStorageSync('corpId');
			this.companyId = uni.getStorageSync('companyId');
		},
		computed: {
			orderStateText() {
				return record => {
					if (record == 'canceled') {
						return '已取消';
					} else if (record == 'uncompleted') {
						return '已下单';
					} else if (record == 'completed') {
						return '已完成';
					}
				};
			},
			balance() {
				if (this.myInfo) {
					return (this.myInfo.walletBalance + this.surplusSubsidyAmount).toFixed(2)
				} else {
					return this.surplusSubsidyAmount
				}
			}
		},
		methods: {
			async initUser() {
				try {
					//如果公司开启了实名登录且token丢失
					if (this.companyInfo.realNameLogin == 1) {
						if (!uni.getStorageSync('token')) {
							uni.redirectTo({
								url: '/pages/companyMemberLogin'
							})
						} else {
							this.hasLogin = true;
							let myInfoResult = await getMyInfo();
							uni.setStorageSync('myInfo', myInfoResult.data.result);
							this.myInfo = myInfoResult.data.result
							if (this.companyInfo.isOpenPersonalPay == 'yes') {
								this._getSurplusSubsidyMoney();
							}
							this._getOrderList();
						}
					} else {
						let loginRes = await loginForCompany({
							name: JSON.parse(localStorage.getItem('myCompanyOrderInfo')).data.username
						});
						this.hasLogin = true;
						let myInfoResult = await getMyInfo();
						uni.setStorageSync('myInfo', myInfoResult.data.result);
						this.myInfo = myInfoResult.data.result
						if (this.companyInfo.isOpenPersonalPay == 'yes') {
							this._getSurplusSubsidyMoney();
						}
						this._getOrderList();
					}
				} catch (error) {
					console.error('error', error);
					this.hasLogin = false;
				}
			},
			async _getOrderList() {
				if (!this.hasLogin) {
					return
				}
				let userId = uni.getStorageSync('myInfo').id
				let params = {
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					userId,
					companyId: uni.getStorageSync('companyId')
				};
				console.log('params', params);
				// let res = await getOrderListWithCompany(params);

				let res = await getOrderListWithCompanyByPage(params);
				console.log('res--------', res);

				res.data.result.records.forEach((item, index) => {
					item.companyOrderDaos.forEach((foodItem, foodIndex) => {
						this.$set(foodItem, 'food', JSON.parse(foodItem.food));
					});
					item.canAfterSales = new Date().getTime() - new Date(item.createTime).getTime() > 1000 *
						60 * 60 * 24 ? false : true;
				});
				if (this.pageNo == 1) {
					this.orderList = res.data.result.records;
				} else {
					this.orderList = [...this.orderList, ...res.data.result.records];
				}
				console.log('this.orderList=', this.orderList);
			},

			goToBack() {
				uni.navigateTo({
					url: '/pages/my/my'
				});
			},
			//展示详细取餐地址
			showAddress(item) {
				console.log('item', item);
				let tempArr = [];
				if (item.supplyAddressImg) {
					tempArr = item.supplyAddressImg.split(',');
					tempArr.forEach(item => {
						if (item.indexOf('http') == -1) {
							item = getApp().globalData.BASE_IMG_URL + item;
						}
					});
				}
				this.addressImgArr = tempArr;
				this.showAddressImg = true;
			},
			async getMyOrderList(type) {
				if (!this.hasLogin) {
					return
				}
				let res = await getMyOrderList({
					pageNo: 1,
					pageSize: this.pageNo * this.pageSize,
					storeName: this.storeName
				});
				console.log('订单列表', res);
				res.data.result.records.forEach(item => {
					item.canAfterSales = new Date().getTime() - new Date(item.createTime).getTime() > 1000 *
						60 * 60 * 24 ? false : true;
				});
				this.orderList = [];
				this.orderList = res.data.result.records;
			},
			goToPage(type, params) {
				let url;
				switch (type) {
					case 'afterSales':
						uni.setStorageSync('afterSaleWithOrderInfo', JSON.stringify(params));
						url = './afterSales';
						break;
					case 'feedback':
						url = `./feedback?id=${params}`;
						break;
					case 'again':
						url = `/pages/index/index?storeName=${params}`;
						break;
					case "confirm":
						url = `/pages/company/confirmOrder`;
						break;
				}
				uni.navigateTo({
					url
				});
			},
			copyInfo(item) {
				let tempUrl = uni.getStorageSync('isSpecial') ? 'https://www.yongshantuan.cn/#/bcwl' :
					'https://www.yongshantuan.cn'
				uni.setClipboardData({
					data: `老板，我在用膳团下单了，送到记得通知我哦～\n${item.pickingSerialNo}号 ${item.nameDishes} ${item.pickingAddress}\n👇👇👇下单：\n${tempUrl}`,
					success: () => {
						//调用方法成功
						uni.hideToast();
						this.warnShow = true;
						this.warnText = '复制成功';
						setTimeout(() => {
							this.warnShow = false;
						}, 5000);
					}
				});
			},
			showCancelModal(index) {
				this.visiable = true;
				this.checkOrderIndex = index;
			},
			//确认取消订单
			async confirm() {
				let res = await cancelOrderWithCompany({
					orderNum: this.orderList[this.checkOrderIndex].orderNum
				});
				console.log('res', res);
				this._getOrderList();
				this.cancel();
			},
			cancel() {
				this.visiable = false;
				this.checkOrderIndex = '';
			},
			showCancelOrder(record) {
				let flag;
				let {
					startTime,
					endTime
				} = uni.getStorageSync('companyInfo');
				let hour = new Date().getHours();
				let miute = new Date().getMinutes();
				let secound = new Date().getSeconds();
				let year = new Date().getFullYear();
				let month = new Date().getMonth() + 1;
				let day = new Date().getDate();
				let fullDate = `${year}/${month}/${day}`;
				let fullStartTime = `${fullDate} ${startTime}`;
				let fullSendTime = `${fullDate} ${endTime}`;
				let startTimeStemp = new Date(fullStartTime).getTime();
				let endTimeStemp = new Date(fullSendTime).getTime();
				if (startTimeStemp < endTimeStemp) {
					if (new Date().getTime() < startTimeStemp || new Date().getTime() > endTimeStemp) {
						return false;
					}
				} else {
					if (new Date().getTime() < startTimeStemp && new Date().getTime() + 24 * 60 * 60 * 1000 >
						endTimeStemp + 24 * 60 * 60 * 1000) {
						return false;
					}
				}
				// return record => {
				if (record.orderState == 'uncompleted' || record.orderState == 'pay' || record.orderState == 'wait') {
					if (!record.companyOrderAfterSalesState) {
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
				// };
			},

			async _getSurplusSubsidyMoney() {
				let params = {
					companyId: this.companyInfo.id,
					userId: this.myInfo.id,
				}
				console.log('-----parmas', params);
				let res = await getSurplusSubsidyMoney(params);
				console.log('补贴余额res', res);
				if (res.data.success) {
					this.surplusSubsidyAmount = res.data.result.surplusSubsidyAmount;
				}
			},
			editMyAccount() {
				uni.removeStorageSync('token');
				uni.removeStorageSync('hasCompanyLogin');
				uni.removeStorageSync('hasNotOverCompanyOrder');
				uni.removeStorageSync('companyOrderCreateResult');
				uni.redirectTo({
					url: '/pages/companyMemberLogin'
				})
			}
		},
		onReachBottom() {
			if (!this.moreOrderFlag) {
				this.moreOrderFlag = true;
				if (this.orderList.length != 0 && this.orderList.length % this.pageSize == 0) {
					this.pageNo = this.pageNo + 1;
					this._getOrderList();
					setTimeout(() => {
						this.moreOrderFlag = false;
					}, 1000);
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.top {
		position: relative;
		height: 40rpx;

		image {
			width: 40rpx;
			height: 40rpx;
			transform: rotate(90deg);
			position: absolute;
			left: 0;
			top: 0;
			z-index: 2;
		}

		text {
			color: #fff;
			width: 100%;
			position: absolute;
			left: 0;
			top: 0;
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
		}

		.note {
			position: absolute;
			right: 0;
			top: calc((100% - 56rpx) / 2);
			font-size: 28rpx;
			line-height: 2;
			color: #fff;
		}
	}

	.indexBig {
		min-height: 100vh;
		background: linear-gradient(0.45deg, #f5f5f5 6.52%, #ff8739 58.65%, #fb690f 98.93%);
		background-size: 100vw 466rpx;
		background-repeat: no-repeat;
		background-color: #f5f5f5;
		padding: 40rpx 20rpx;
		padding-bottom: 150rpx;

		.top {
			position: relative;

			image {
				width: 40rpx;
				height: 40rpx;
				transform: rotate(90deg);
			}

			text {
				width: 100%;
				position: absolute;
				left: 0;
				top: 0;
				text-align: center;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.searchBox {
			margin: 10rpx auto;
			margin-top: 40rpx;
			background-color: #fff;
			border-radius: 20rpx;
			padding: 0 20rpx;
			@include flexs();

			image {
				width: 50rpx;
				height: 50rpx;
			}

			view {
				width: calc(28rpx * 2);
				font-size: 28rpx;
				line-height: 2;
				color: #f3b209;
				padding: 10rpx 0;
			}
		}

		.walletBox {
			background-color: #fff;
			border-radius: 20rpx;
			margin: 40rpx 0 20rpx 0;
			padding: 20rpx 20rpx;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.05);
			@include flexs(space-between, center);

			>view {
				@include flexs();

				image {
					width: 50rpx;
					height: 50rpx;
					margin-right: 20rpx;
				}

				&:nth-child(2) {
					font-weight: bold;
				}
			}
		}

		.allBox {
			margin: 40rpx 0;

			>view {
				background-color: #fff;
				padding: 40rpx 20rpx;
				border-radius: 20rpx;
				margin: 20rpx 0;
			}

			.list {
				position: relative;
				padding: 0 0 10px 0;
				text-align: center;

				&:last-child {
					border: 0;
				}

				.listTop {
					@include flexs();
					margin-bottom: 28rpx;

					image {
						width: 68rpx;
						height: 68rpx;
						margin-right: 10rpx;
						border-radius: 16rpx;
						border: 1px solid #eee;
					}

					>view:nth-child(2) {
						flex: 1;
						font-size: 26rpx;
						font-weight: bold;
						text-align: left;
						margin-left: 10px;
					}

					>view:nth-child(3) {
						font-size: 28rpx;
						color: rgba(0, 0, 0, 0.55);
					}
				}

				.content {
					width: 100%;
					overflow-x: auto;
					padding: 20rpx 0 0 0;
					position: relative;

					/*定义滚动条高宽及背景高宽分别对应横竖滚动条的尺寸*/
					&::-webkit-scrollbar {
						width: 0;
						height: 0;
						background-color: #f5f5f5;
					}

					/*定义滚动条轨道内阴影+圆角*/
					&::-webkit-scrollbar-track {
						-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
						border-radius: 0;
						background-color: #f5f5f5;
					}

					/*定义滑块内阴影+圆角*/
					&::-webkit-scrollbar-thumb {
						border-radius: 0;
						-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
						background-color: #555;
					}

					.imgContent {
						width: 120000px;
						@include flexs();
					}

					.foodContent {
						width: 140rpx;
						font-size: 24rpx;
						line-height: 1.5;
						margin-right: 30rpx;

						text {
							text-overflow: ellipsis;
							overflow: hidden;
							white-space: nowrap;
							width: 100%;
							display: block;
						}

						image {
							width: 140rpx;
							height: 140rpx;
							border-radius: 8rpx;
						}
					}
				}

				.warn {
					position: absolute;
					width: 180rpx;
					height: 140rpx;
					right: 0;
					top: 120rpx;
					background: linear-gradient(272.26deg, #ffffff 2.33%, rgba(255, 255, 255, 0.86) 76.83%, rgba(255, 255, 255, 0.63) 134.87%);
					@include flexs(center, center);
					flex-direction: column;

					>view:nth-child(1) {
						font-size: 36rpx;
						line-height: 1.5;
						font-weight: bold;
					}

					>view:nth-child(2) {
						font-size: 28rpx;
						line-height: 1.5;
						color: rgba(0, 0, 0, 0.55);
					}
				}

				.button {
					display: inline;
					padding: 0 20rpx;
					font-size: 24rpx;
					line-height: 2;
					color: #fa690a;
					border: 1px solid #fa690a;
					border-radius: 100rpx;
					float: right;
					margin: 20rpx 0 0 0;
				}
			}

			.afterSales {
				font-size: 28rpx;
				line-height: 2;
				text-align: left;
				color: #666;
				margin-top: 10px;
			}

			.orderTop {
				@include flexs(space-between, center);
				font-size: 14px;
				line-height: 2;

				>view {
					font-size: 14px;
					color: #666;
				}
			}

			.orderInfo {
				font-size: 28rpx;
				line-height: 1.5;
			}

			.bottom {
				@include flexs(space-between, center);
				padding: 10rpx 0 0 0;

				>view:nth-child(2) {
					@include flexs(flex-end, center);
				}

				.button {
					display: inline;
					padding: 0 15rpx;
					font-size: 24rpx;
					line-height: 2;
					color: #fa690a;
					border: 1px solid #fa690a;
					border-radius: 100rpx;
					margin-left: 10rpx;
				}
			}

			.show-time {
				font-size: 11px;
				line-height: 2;
				color: #666;
			}
		}

		.empty {
			background-color: #fff;
			border-radius: 10rpx;

			.u-empty {
				min-height: 50vh;
			}
		}

		.addressImgBox {
			@include flexs(center, center);
			flex-direction: column;
			padding: 20rpx 0;

			.title {
				font-size: 32rpx;
				line-height: 2;
				margin-bottom: 20rpx;
			}

			image {
				max-width: 100%;
				margin-bottom: 10rpx;
			}

			/deep/ {
				.u-empty {
					padding: 80rpx 0;
					background-color: #fff;
					width: calc(100% - 40rpx);
					margin: 0 auto;
					border-radius: 10rpx;
				}
			}
		}
	}

	.warnBox {
		width: 100%;
		height: 100vh;
		@include flexs(center, center);
		position: fixed;
		left: 0;
		top: 0;
		transition: all 0.2s;
		display: none;

		>view {
			width: 80%;
			height: 100rpx;
			background-color: rgba(0, 0, 0, 0.7);
			border-radius: 20rpx;
			color: #fff;
			@include flexs(center, center);
			padding: 80rpx 40rpx;
		}
	}

	.warnBoxShow {
		display: flex;
	}
</style>

<style lang="scss">
	.addressImgContent {
		/deep/.u-drawer-top {
			max-height: 80vh;
			overflow-y: scroll;
		}

		/deep/ {
			.u-drawer__scroll-view {
				max-height: 80vh;
			}
		}
	}
</style>